<?php

namespace App\Task;

use App\Utils\LiveApi;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Logger\LoggerFactory;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Log\LoggerInterface;
use function Hyperf\Support\env;
use function Hyperf\Support\make;

abstract class AbstractBaseTask
{

    protected LoggerInterface $logger;
    protected LiveApi $api;

    public function __construct(protected ContainerInterface $container)
    {
        try {
            $this->logger = $this->container->get(LoggerFactory::class)->get(ltrim(substr(get_called_class(), strrpos(get_called_class(), '\\')), '\\'), 'task');
            $this->api = make(LiveApi::class, ['gateway' => env('TARGET_API_GATEWAY', ''), 'requestDelayTime' => floatval(env('TARGET_API_REQUEST_DELAY', 0))]);
        } catch (ContainerExceptionInterface|NotFoundExceptionInterface $e) {
        }
    }

    abstract public function execute();

    /**
     * 休眠等待
     * @param $seconds
     * @return void
     */
    protected function sleep($seconds): void
    {
        if (Coroutine::inCoroutine()) {
            \Swoole\Coroutine::sleep($seconds);
        } else {
            usleep($seconds * 1000 * 1000);
        }
    }
}